`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    09:42:00 12/29/2020 
// Design Name: 
// Module Name:    MULT_DIV 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module MULT_DIV(
	input clk,
	input reset,
	input [31:0]D1,
	input [31:0]D2,
	input specialWrite,
	input Start,
	input isHI,
	input isDIV,
	input isSigned,
	output [31:0]Data,
	output busy
    );
	integer i;
	wire [63:0]prod;
	reg [32:0] HI, LO;
	wire [32:0]tempD1, tempD2;
	reg [5:0]count, target;
	
	assign tempD1 = {{1'b0}, D1};
	assign tempD2 = {{1'b0}, D2};
	assign Data = isHI ? HI : LO;
	assign tempD1 = {{1'b0}, D1};
	assign tempD2 = {{1'b0}, D2};
	assign busy = (count < target);
	assign prod = isSigned ? $signed( $signed({{32{D1[31]}},D1}) * $signed({{32{D2[31]}},D2}) ) : tempD1 * tempD2; 
	always @(posedge clk)
	begin 
		if(reset)
		begin 
			HI <= 0;
			LO <= 0;
			count = 0;
			target <= 0;
			
		end
		else begin
			if(Start)
			begin
				
				
				count = 0;
				if(isDIV)
				begin
					target = 10;
					if(D2 == 0);						
					else if(isSigned)
					begin
						LO <= $signed(D1) / $signed(D2);
						HI <= $signed(D1) % $signed(D2);
					end
					else if(~isSigned)
					begin
						LO <= tempD1 / tempD2;
						HI <= tempD1 % tempD2;
					end
				end
				else if(~isDIV)
				begin
					target = 5;
					HI <= prod[63:32];
					LO <= prod[31:0];
				end
			end
			if(specialWrite)
			begin
				if(isHI)
					HI <= D1;
				else if(~isHI)
					LO <= D1;
			end
			
			if(count < target)
			begin
				count <= count+1;
			end
			else 
			begin
				target = 0;
				count = 0;
			end
		end
	end
	
endmodule
